<template>
    <div class="chat-container">
      <div class="header">
        <h1>DeepSeek AI 聊天助手</h1>
      </div>
      
      <div class="messages-container" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" class="message" :class="message.role">
          <div class="message-header">
            <span class="role">{{ message.role === 'user' ? '用户' : 'AI' }}</span>
            <span class="time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="message-content">
            <template v-if="message.isThinking">
              <div class="typing">
                <span class="dot"></span>
                <span class="dot"></span>
                <span class="dot"></span>
              </div>
            </template>
            <template v-else>
              <div v-html="renderMarkdown(message.content)"></div>
            </template>
          </div>
        </div>
      </div>
      
      <div class="input-container">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入消息，按Enter发送，Ctrl+Enter换行"
          @keydown.enter.exact.prevent="sendMessage"
          @keydown.ctrl.enter="newLine"
        />
        <el-button 
          type="primary" 
          :loading="isLoading" 
          @click="sendMessage"
          :disabled="!inputMessage.trim()"
        >
          {{ isLoading ? '发送中...' : '发送' }}
        </el-button>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, computed, onMounted, nextTick, watch } from 'vue'
  import { useStore } from 'vuex'
  import { marked } from 'marked'
  import { ElMessage } from 'element-plus'  
  import api from '@/utils/api'  
  
  export default {
    name: 'ChatView',
    setup() {
      const store = useStore()
      const inputMessage = ref('')
      const messagesContainer = ref(null)
      const streamingContent = ref('')
      const currentSession = ref(null)  
      
      const messages = computed(() => store.getters.getMessages)
      const isLoading = computed(() => store.getters.isLoading)
      
      // 监听消息流
      watch(() => store.state.currentStreamContent, (newContent) => {
        streamingContent.value = newContent
      })
      
      // 发送消息
      const sendMessage = async () => {
        if (!inputMessage.value.trim()) return
        
        const userMessage = inputMessage.value
        inputMessage.value = ''
        
        // 添加用户消息到消息列表
        messages.value.push({
          role: 'user',
          content: userMessage
        })
        
        // 添加一个临时的 AI 思考消息
        messages.value.push({
          role: 'assistant',
          content: '思考中...',
          isThinking: true  // 添加标记用于显示动画
        })
        
        try {
          isLoading.value = true
          
          const response = await api.post('/chat/send', {
            content: userMessage,
            sessionId: currentSession.value?.sessionId
          })
          
          const aiMessage = response.data.message
          
          messages.value[messages.value.length - 1] = {
            role: 'assistant',
            content: aiMessage.content
          }
          
          // 使用打字机效果显示 AI 回复
          let displayedContent = ''
          const content = aiMessage.content
          
          for (let i = 0; i < content.length; i++) {
            displayedContent += content[i]
            messages.value[messages.value.length - 1] = {
              role: 'assistant',
              content: displayedContent
            }
            await nextTick()
            if (messagesContainer.value) {
              messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
            }
            await new Promise(resolve => setTimeout(resolve, 10))
          }
          
          // 更新会话 ID（如果是新会话）
          if (response.data.sessionId) {
            currentSession.value = {
              sessionId: response.data.sessionId,
              title: userMessage.substring(0, 20)
            }
          }
          
        } catch (error) {
          ElMessage.error('发送消息失败：' + error.message)
        } finally {
          isLoading.value = false
        }
      }
      
      // 加载历史消息
      onMounted(() => {
        store.dispatch('loadChatHistory')
      })
      
      // 监听消息变化，自动滚动到底部
      watch(messages, () => {
        nextTick(() => {
          if (messagesContainer.value) {
            messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
          }
        })
      })
      
      // 换行
      const newLine = () => {
        inputMessage.value += '\n'
      }
      
      // 格式化时间
      const formatTime = (timestamp) => {
        if (!timestamp) return ''
        const date = new Date(timestamp)
        return date.toLocaleString()
      }
      
      // 渲染Markdown
      const renderMarkdown = (content) => {
        if (!content) return ''
        return marked(content)
      }
      
      return {
        inputMessage,
        messages,
        isLoading,
        messagesContainer,
        streamingContent,  // 添加这行
        sendMessage,
        newLine,
        formatTime,
        renderMarkdown
      }
    }
  }
  </script>
  
  <style scoped>
  .chat-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .header {
    text-align: center;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
  }
  
  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px 0;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .message {
    max-width: 80%;
    padding: 15px;
    border-radius: 10px;
    position: relative;
  }
  
  .message.user {
    align-self: flex-end;
    background-color: #e1f3ff;
  }
  
  .message.assistant {
    align-self: flex-start;
    background-color: #000; /* 改为黑色背景 */
    color: #00f3ff; /* 添加赛博朋克风格文字颜色 */
    border: 1px solid #00f3ff; /* 添加边框效果 */
  }
  
  /* 确保代码块在黑色背景下可读 */
  .message-content :deep(pre) {
    background-color: #1a1a1a;
    color: #00f3ff;
    padding: 10px;
    border-radius: 5px;
    overflow-x: auto;
  }
  
  .message-content :deep(code) {
    background-color: #1a1a1a;
    color: #00f3ff;
    padding: 2px 4px;
    border-radius: 3px;
  }
  
  .input-container {
    display: flex;
    gap: 10px;
    padding: 20px 0;
    border-top: 1px solid #eee;
  }
  
  .input-container .el-textarea {
    flex: 1;
  }
  
  .typing {
    display: flex;
    align-items: center;
    gap: 5px;
  }
  
  .dot {
    width: 8px;
    height: 8px;
    background-color: #999;
    border-radius: 50%;
    animation: typing 1.5s infinite ease-in-out;
  }
  
  .dot:nth-child(2) {
    animation-delay: 0.2s;
  }
  
  .dot:nth-child(3) {
    animation-delay: 0.4s;
  }
  
  @keyframes typing {
    0%, 60%, 100% {
      transform: translateY(0);
    }
    30% {
      transform: translateY(-5px);
    }
  }
  </style>